package com.ruoyi.web.config.documentUtil;

import com.aspose.words.*;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;

import static com.ruoyi.common.utils.file.FileUtils.*;

@Slf4j
@Component
public class DocumentUtil {

    @Value("${PDFConvert.fontFolder}")
    public String fontFolder;

    /**
     * 上传文件到本地
     */
    public boolean uploadDocument(InputStream in,String code,String suffix){
        boolean result = false;
        code = RuoYiConfig.getPdfPath()+"/" + code +"."+suffix;
        try {
            inputStream2File(in,new File(code));
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 下载文件到本地
     */
    public byte[] downloadDocument(String key,String suffix){
        key = RuoYiConfig.getPdfPath()+"/" + key + "."+suffix;
        return File2byte(key);
    }

    /**
     * 删除文件到本地
     */
    public void deleteDocument(String key,String suffix){
        key = RuoYiConfig.getPdfPath()+"/" + key + "."+suffix;
        File file = new File(key);
        if (file.exists()){
            file.deleteOnExit();
        }
    }


    //项目启动时加载
    @PostConstruct
    public void getLicense(){
        try {
            InputStream is = DocumentUtil.class.getClassLoader().getResourceAsStream("license.xml"); //Test要替换成当前类名  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License AsposeLic = new License();
            AsposeLic.setLicense(is);
            FontSettings.setFontsFolder(fontFolder, false);//设置字体文件夹
            if (is != null) {
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * word文件转换
     */
    public byte[] convertDocument(InputStream in){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] result = null;
        try {
            Document doc = new Document(in);
            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            result = os.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public byte[] convertWordToPdf(InputStream wordFile){
        File f = null;
        try {
            f = File.createTempFile("convert", ".docx");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            FileUtils.inputStream2File(wordFile,f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        File f1 = null;
        try {
            f1 = File.createTempFile("convert", ".pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
        convertWordToPdf(f.getAbsolutePath(),f1.getAbsolutePath());

        return FileUtils.File2byte(f1);
    }

    public void convertWordToPdf(String wordFile, String pdfFile){
        File file = new File(wordFile);
        if(file.exists()){
            if (!file.isDirectory()) {   //判断word文件存不存在
                ActiveXComponent app = null;
                try {
                    //新增优化代码==============>初始化com的线程
                    // ComThread.InitSTA();   仅允许线程池里面的一个线程执行，其他线程都被锁住
                    ComThread.InitMTA(true);  //允许同时有多个WORD进程运行
                    // 打开word
                    app = new ActiveXComponent("Word.Application");
                    // 设置word不可见
                    app.setProperty("Visible", false);
                    // 获得所有打开的文档
                    Dispatch documents = app.getProperty("Documents").toDispatch();
                    // 打开文档
                    Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
                    // 判断文件是否存在
                    File target = new File(pdfFile);
                    if (target.exists()) {
                        target.delete();
                    }
                    // 另存为，将文档报错为pdf，其中word保存为pdf的格式宏的值是17
                    Dispatch.call(document, "SaveAs", pdfFile, 17);
                    // 关闭文档
                    Dispatch.call(document, "Close", false);
                }catch(Exception e) {
                    throw new RuntimeException("pdf转换失败！请联系技术人员。");
                }finally {
                    // 关闭office
                    if (app != null) {
                        app.invoke("Quit", new Variant[] {});
                    }
                    //新增优化代码==============>关闭com的线程
                    ComThread.Release();
                }
            }
        }
    }
    /**
     * 判断OSS服务文件上传时文件的contentType
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase("pdf")) {
            return "application/pdf";
        }
        return "image/jpeg";
    }
}
